<!DOCTYPE html>
<html lang="en">
	<head>
		<title>demo</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">
	</head>
<body>

<script src="./socket/socket.io.js"></script>
<script type="module">
import * as THREE from '../build/three.module.js';

var reload = false

var socket = io.connect(window.location.origin);
socket.on('connect', function() {
    console.log("connect to server")
});


socket.on('test', function() {
    if (!reload){
        socket.emit("test")
        reload = true
    }
    else{
        setTimeout(() => {
            location.reload();
        }, 0);
    }
})

const scene = new THREE.Scene();
scene.background = new THREE.Color( 0xcce0ff );
scene.fog = new THREE.Fog( 0xcce0ff, 500*10, 10000 );
scene.add( new THREE.AmbientLight( 0x666666 ) );

const camera = new THREE.OrthographicCamera( -1.0, 1.0, 1.0, -1.0, 1, 2000 );
camera.position.z = 5;

const renderer = new THREE.WebGLRenderer({
    antialias: true,
    preserveDrawingBuffer:true,
});
document.body.appendChild( renderer.domElement );

var camera_scale = 0.2

function onWindowResize() {
    const k = 1200.0 * camera_scale
    camera.left = - window.innerWidth / k
    camera.right = window.innerWidth / k
    camera.top = window.innerHeight / k
    camera.bottom = - window.innerHeight / k
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

}

onWindowResize()

window.addEventListener( 'resize', onWindowResize );

socket.on('lockCamera', function(e) {
    camera.position.x = e[0]
    camera.position.y = e[1]
})

const animate = function () {
    requestAnimationFrame( animate );
    raycaster.setFromCamera( mouse, camera );
    var k = raycaster.ray.origin.z / raycaster.ray.direction.z * (- 1.0)
    var x, y;
    x = raycaster.ray.origin.x + k * raycaster.ray.direction.x
    y = raycaster.ray.origin.y + k * raycaster.ray.direction.y
    if (isMoveE){
        socket.emit("controlE", [x, y])
    }
    if (isLockCamera){
        socket.emit("getE")
    }
    if (!isLockCamera && !isMoveE){
        camera.position.x += 0.1 * (x - camera.position.x)
        camera.position.y += 0.1 * (y - camera.position.y)
    }
    renderer.render( scene, camera );
};

setTimeout(() => {
    animate()
}, 0);

const loader = new THREE.TextureLoader();
socket.on('background', function() {
    var groundTexture = loader.load( 'textures/f.png' );
    groundTexture.encoding = THREE.sRGBEncoding;
    const geometry = new THREE.PlaneGeometry( 1, 1 );
    const material = new THREE.MeshBasicMaterial( {map: groundTexture} );
    const plane = new THREE.Mesh( geometry, material );
    scene.add( plane )
});

function Ball(color, r=0.05) {
    var geometry = new THREE.SphereGeometry( r, 32, 32 );
    var material = new THREE.MeshBasicMaterial( { color } );
    var ball = new THREE.Mesh( geometry, material );
    scene.add( ball );
    return ball
}

const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();

function getXYFromMouse(event) {
	mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
	mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
    raycaster.setFromCamera( mouse, camera );
}

function onMouseMove( event ) {
	mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
	mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}

window.addEventListener( 'mousemove', onMouseMove, false );

function onWheel( event ) {
    camera_scale += event.deltaY / 1000.0
    console.log(camera_scale)
    onWindowResize()
}
// window.addEventListener( 'wheel', onWheel, false );

var obj = {}

socket.on("scatter", function([id, x, y, color]) {
    if (typeof(id) === 'number'){
        id = [id]
        x = [x]
        y = [y]
        color = [color]
    }
    for(var i=0; i<id.length; ++i){
        var b = Ball(color[i])
        if (obj[id[i]]){
            scene.remove(obj[id[i]])
        }
        obj[id[i]] = b
        b.position.x = x[i]
        b.position.y = y[i]
    }
})

socket.on("scatter2", function([id, x, y]) {
    if (typeof(id) === 'number'){
        id = [id]
        x = [x]
        y = [y]
    }
    for(var i=0; i<id.length; ++i){
        var b = obj[id[i]]
        b.position.x = x[i]
        b.position.y = y[i]
    }
})

socket.on("plot", function([id, x, y, color]) {
    var p = []
    for(var i=0; i<x.length; ++i){
        p.push(new THREE.Vector2( x[i], y[i] ))
    }
    const points = p;
    const geometry = new THREE.BufferGeometry().setFromPoints( points );
    const material = new THREE.LineBasicMaterial( { color } );
    const splineObject = new THREE.Line( geometry, material );
    if (obj[id]){
        scene.remove(obj[id])
    }
    obj[id] = splineObject
    scene.add(splineObject)
})

socket.on("delobj", function(id) {
    for(var i=0; i<id.length; ++i){
        if (obj[id[i]]){
            scene.remove(obj[id[i]])
            delete obj[id[i]]
        }
    }
})

var isLockCamera = true
var isMoveE = false

function onKeydown(e) {
    if (e.code == "Space"){
        isLockCamera = !isLockCamera
    }
    if (e.code == "KeyM"){
        isMoveE = !isMoveE
    }
}


window.addEventListener( 'keydown', onKeydown, false );

</script>

</body>
</html>